import { useRequest } from 'ahooks';
import { useParams } from 'react-router-dom';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { getQuestionList } from '@/services/question';
import { resetComponents } from '@/store/ComponentsReducer';
import { resetPageInfo } from '@/store/PageInfoReducer';

function useLoadQuestion() {
  const { id = '' } = useParams();
  const dispatch = useDispatch();

  const { loading, data, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error('id不能为空');
      const res = await getQuestionList(id);
      return res;
    },
    {
      manual: true,
    }
  );

  useEffect(() => {
    if (!data) return;
    const {
      title,
      desc = '',
      js = '',
      css = '',
      isPublished = false,
      componentList = [],
    } = data;
    let selectedId = '';
    if (componentList.length) {
      selectedId = componentList[0].fe_id;
    }
    dispatch(
      resetComponents({
        componentList,
        selectedId,
        copiedComponent: null,
      })
    );
    dispatch(resetPageInfo({ title, desc, js, css, isPublished }));
  }, [data, dispatch]);

  useEffect(() => {
    run(id);
  }, [id, run]);

  return { loading, error };
}

export default useLoadQuestion;
